-- 队伍模块
-- Author: Colocasia
-- Date: 2019-10-17

local us = require 'us';
local tool = require 'tool';
local class = require 'class';
local handler = require 'handler';

local table = require 'us.table';
local table_merge = table.merge;
local table_clone = table.clone;
local table_foreach = table.foreach;

local team_mgr = require 'team_mgr';
local insert_team = team_mgr.insert;
local remove_team = team_mgr.remove;
local get_team = team_mgr.get_team;

local ENUM_TEAM = require 'team_const';

local M = class("team", handler);

-- 队伍数据
local team = {
    guid    = '',                           -- 队伍GUID
    server  = '',                           -- 队伍所属服务器
    service = us:self(),                    -- 队伍服务地址
    state   = ENUM_TEAM.STATE.IDLE,         -- 队伍状态
    players = {},                           -- 队伍中的玩家
    list    = '',                           -- 队伍所在匹配列表
}

function M:ctor()
    self.guid = tool:guid();
    table_merge({self, table_clone(team)}, true);
    insert_team(self);
end

---创建队伍
function M:create_team(players)
    local team = M.create();
    table_foreach(players or {}, function(player)
        self:insert(team.guid, player);
    end)
end

---获取队伍玩家数量
function M:player_count(guid)
    local team = get_team(guid);
    return team and #team.players or 0;
end

---是否存在玩家
function M:exist(guid, player)
    local team = get_team(guid);
    if not team then return 0 end

    local exist = 0;
    table_foreach(team.players, function(p, i)
        if p.guid == player.guid then
            exist = i;
        end
    end)
    return exist;
end

---添加玩家进队伍
function M:insert(guid, player)
    local team = get_team(guid);
    if not team then return self:code('team_not_exist') end
    if self:player_count(guid) >= ENUM_TEAM.MAX_PLAYER then return self:code('team_is_full') end
    if self:exist(guid, player) > 0 then return self:code('team_already_in') end
    
    table.insert(team.players, player);

end

---从队伍移除玩家
function M:remove(guid, player)
    local team = get_team(guid);
    if not team then return self:code('team_not_exist') end
    
    local index = self:exist(guid, player);
    if index < 1 then return self:code('team_not_exist_player') end

    table.remove(team.players, index);

    if self:player_count(guid) < 1 then
        self:delete_team(guid);
    end
end

---删除队伍
function M:delete_team(guid)
    local team = get_team(guid);
    if not team then return self:code('team_not_exist') end

    remove_team(team);

end

---获取队伍信息
function M:get_info(guid)
    local team = get_team(guid);
    if not team then return self:code('team_not_exist') end
    return table_clone(team);
end

return M;
